myApp.controller('UCReleaseController', function ($scope,$http,$stateParams,$uibModal,ngDialog,$sce) {

    $scope.info={};

    $scope.info.selectVm=$stateParams.selectVm;
    $scope.info.vmInfo={};
    $scope.info.vmStatus="";

    $scope.info.zones=[];
    $scope.info.tabIndex=0;
    $scope.info.selectZone={};
    $scope.info.apps=[];

    $scope.info.checkAll=false;
    //执行构建的工程列表
    $scope.info.buildList=[];

    $scope.info.userRole = getUserRole();

    $scope.socket = null;

    $scope.info.doRunList = [];

    $scope.arrayContains = function (array,obj) {
        return arrayContains(array,obj);
    };


    var wsObj = wsObjs[0];
    $scope.$on("$destroy", function() {
        if($scope.socket != null){
            $scope.socket.close();
        }
    });

    //获取vm信息
    if($scope.info.selectVm!=''){
        $http.post(java_url+'/beetle/uCloud/getUCloudInfo', {
            tokenId:getTokenId(),
            name:$scope.info.selectVm
        }).success(function (data) {
            if(data.code=='0'){
                $scope.info.vmInfo=data.data.info;
                getZones();
                uCloudSocket();
            }else {
                alert("获取虚拟机信息为空!");
            };
        });
    }else {
        $scope.info.vmInfo={};
    };

    $scope.wsWithReConnect = function () {
        wsWithReConnect(wsObj, function () {
            angular.forEach($scope.info.buildList,function (name) {
                wsObj.obj.send("project-" + name + "-build");
            });
        }, function (event) {
            var data = JSON.parse(event.data);
            if (data.head.type == 'project_build_status') {
                var projectName = data.body.projectName;
                var status = data.body.status;
                $scope.$apply(function () {
                    angular.forEach($scope.info.apps,function (app) {
                        if(typeof app.projectInfo != 'undefined'
                            && app.projectInfo.projectName == projectName){
                            app.pipeline_status = status;
                            $scope.doRun(app);
                            if("build_failed"==status){
                                app.last_msg = '[ERROR]'+data.body.desc;
                            }else {
                                app.last_msg = data.body.desc;
                            }
                            app.projectInfo.buildStatus=status;
                            if(("build_failed"==status || "build_success"==status)){
                                app.isRunning=false;
                                for(var i=0;i<$scope.info.buildList.length;i++){
                                    if(projectName == $scope.info.buildList[i]){
                                        $scope.info.buildList.splice(i,1);
                                        getProjectInfo(app);
                                        break;
                                    }
                                }
                            }
                        }
                    });
                });
            }else if(data.head.type == 'project_push_status'){//工程跳板机推送状态
                var projectName = data.body.projectName;
                var status = data.body.status;
                $scope.$apply(function () {
                    angular.forEach($scope.info.apps,function (app) {
                        if(typeof app.projectInfo != 'undefined'
                            && app.projectInfo.projectName == projectName){
                            app.pipeline_status = status;
                            $scope.doRun(app);
                            if("push_error"==status || "push_exception"==status){
                                app.last_msg = '[ERROR]'+data.body.desc;
                            }else {
                                app.last_msg = data.body.desc;
                            }
                            app.projectInfo.pushStatus=status;
                            if("push_success"==status || "push_error"==status || "push_exception"==status){
                                app.isRunning=false;
                                for(var i=0;i<$scope.info.buildList.length;i++){
                                    if(projectName == $scope.info.buildList[i]){
                                        $scope.info.buildList.splice(i,1);
                                        getProjectInfo(app);
                                        break;
                                    }
                                }
                            }
                        }
                    });
                });
            };
        });
    };

    $scope.wsWithReConnect();

    function uCloudSocket() {
        var ip = $scope.info.vmInfo.ip;
        if(typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == ''){
            return;
        };
        $scope.socket = io.connect('http://'+ip+':5000/notify',{'forceNew':true });
        $scope.socket.on("stat", function(msg) {
            var data = msg.data.replace(new RegExp(/(None)/g),"''");
            console.log(data);
            if(data == 'Connected'){
                return;
            }
            data = eval("(" + data + ")");
            if(typeof data.name == 'undefined' || data.name == ''){
                return;
            }
            if(typeof data.app == 'undefined' || data.app == ''){
                return;
            }
            if(typeof data.pipeline == 'undefined' || data.pipeline == ''){
                return;
            }
            // if(typeof data.pipeline.group == 'undefined' || data.pipeline.group == ''){
            //     return;
            // }
            $scope.$apply(function () {
                angular.forEach($scope.info.apps,function (app) {
                    if(data.name == 'container_app_event'){
                        container_app_event(app,data);
                    }
                });
            });
        });
    };

    function container_app_event(app,data) {
        if(app.app_id==data.app.app_id){
            $scope.doRun(app);
            app.pipeline_status=data.pipeline.status;
            app.status=data.app.status;
            app.is_running=data.app.is_running;
            app.last_msg=data.app.last_msg;
            app.running_pipeline=data.app.running_pipeline;
            app.db_dump_create_date=data.app.db_dump_create_date;
            app.app_package_create_date=data.app.app_package_create_date;
            if(data.app.running_pipeline != null){
                app.isRunning = true;
                return;
            }
            app.isRunning = false;

            if(app.pipeline_status == 'DONE'){
                app.version = data.app.version.replace('.version','');
            }
        }
    }

    //tab切换
    $scope.tabClick = function (index,zone) {
        $scope.info.tabIndex = index;
        $scope.info.selectZone = zone;
        $scope.info.apps=[];
        $scope.info.checkAll=false;
        //查询app列表
        var ip = $scope.info.vmInfo.ip;
        if(typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == ''){
            alert("虚拟机ip为空!");
            return;
        };
        $http.get(getUCloudAddress(ip)+"/apps/?zone_code="+zone.zone_code,{
            headers : {'Accept':'application/json'}
        }).success(function (data) {
            $scope.info.vmStatus="running";
            $scope.info.apps=data;
            angular.forEach($scope.info.apps,function (app) {
                app.version = app.version.replace(".version","");
                app.onlineVersion = '';
                console.log(JSON.stringify(app));
                app.ucUrl = "";
                angular.forEach(ucloud_project_url,function (url) {
                    if(url.name == app.app_name){
                        app.ucUrl = url.url;
                    }
                });

                // if(app.status == 'running' || app.status == 'RUNNING' || app.running_pipeline != null){
                if(app.status == 'running' || app.status == 'RUNNING'){
                    app.isRunning = true;
                    $scope.doRun(app);
                }else{
                    app.isRunning = false;
                };

                if(arrayContains($scope.info.doRunList,app.app_id)){
                    app.doRun = true;
                }
            });
            getAppInfo();

        }).error(function () {
            $scope.info.vmStatus="error";
        });

    };
    //全选事件
    $scope.checkAll = function () {
        angular.forEach($scope.info.apps,function (app) {
            app.check = $scope.info.checkAll;
        });
    };

    $scope.tr_color = function (app) {
        if(typeof app.projectInfo == 'undefined'
            || typeof app.editionInfo == 'undefined'){
            return "";
        }
        var version = app.projectInfo.projectName+"#"+app.editionInfo.editionNum;
        if(app.onlineVersion == version){
            return "online";
        }else if(app.qaTestVersion == version){
            return "qaTest";
        }
        return "";
    };
    //project变动
    $scope.projectChange = function (app) {
        if(app.app_type == 'adempiere'){
            $http.post(java_url+'/beetle/uCloud/adEditionList', {
                projectName: app.projectInfo.projectName,
                tokenId:getTokenId()
            }).success(function (data) {
                if (data.code != '0') {
                    alert("获取工程信息失败,desc=" + data.desc);
                    return;
                };
                app.editionList = data.data.list;
                if(app.editionNum == ''){
                    app.editionInfo = data.data.list[0];
                }else {
                    var count = 0;
                    angular.forEach(data.data.list,function (edi) {
                        if(edi.editionNum == app.editionNum){
                            count = 1;
                            app.editionInfo = edi;
                        }
                    });
                    if(count == 0){
                        app.editionInfo = data.data.list[0];
                    }
                };
            });
        }else {
            $http.post(java_url+'/beetle/project/editionInfoList', {
                projectName: app.projectInfo.projectName,
                tokenId:getTokenId()
            }).success(function (data) {
                if (data.code != '0') {
                    alert("获取工程信息失败,desc=" + data.desc);
                    return;
                };
                app.editionList = data.data.list;
                if(app.editionNum == ''){
                    if(data.data.list.length > 1){
                        app.editionInfo = data.data.list[1];
                    }else {
                        app.editionInfo = data.data.list[0];
                    }
                }else {
                    var count = 0;
                    angular.forEach(data.data.list,function (edi) {
                        if(edi.editionNum == app.editionNum){
                            count = 1;
                            app.editionInfo = edi;
                        }
                    });
                    if(count == 0){
                        if(data.data.list.length > 1){
                            app.editionInfo = data.data.list[1];
                        }else {
                            app.editionInfo = data.data.list[0];
                        }
                    }
                };
            });
        }
    };

    $scope.editionChange = function (app) {
        if(app.app_type == 'adempiere'){
            return;
        }
        if((app.projectInfo.buildStatus == 'on_build'
            || app.projectInfo.buildStatus == 'in_queue')
            && app.editionInfo.editionNum == 'default'){
            app.isRunning = true;
            app.status = app.projectInfo.buildStatus;
            $scope.info.buildList.push(app.projectInfo.projectName);
            wsObj.obj.send("project-" + app.projectInfo.projectName + "-build");
        }
    };

    //操作按钮展示判断
    $scope.btnShow = function (type,app,index) {
        //按钮一直存在,可点不可点状态
        if(index == 0){
            // if(app.db_status != "ready" && app.db_status != "READY"){
            //     app.last_msg = "应用数据库未准备好!";
            //     return false;
            // }



            if(type == 'release'){
                if((app.on_beetle == 'false'
                    || (typeof app.projectInfo != 'undefined'
                    && typeof app.editionInfo != 'undefined'))){
                    return true;
                }
            }









            if(app.isRunning){
                return false;
            }
            if(type == 'build'){
                if(app.on_beetle == 'false'){
                    return false;
                }
                if(app.app_type != 'adempiere'
                    && typeof app.projectInfo != 'undefined'
                    && typeof app.editionInfo != 'undefined'
                    && app.editionInfo.editionNum == 'default'){
                    return true;
                }
            }else if(type == 'release'){
                if((app.on_beetle == 'false'
                    || (typeof app.projectInfo != 'undefined'
                    && typeof app.editionInfo != 'undefined'))){
                    return true;
                }
            }else if(type == 'stop'){
                if(app.version != '-1'
                    && app.status != 'unavailable'
                    && app.status != 'UNAVAILABLE'){
                    return true;
                }
            }else if(type == 'restart'){
                // if(app.version != '-1'
                //     && app.status != 'unavailable'
                //     && app.status != 'UNAVAILABLE'){
                //     return true;
                // }
                return true;
            }else if(type == 'check'){
                if(typeof app.projectInfo == 'undefined'
                    || typeof app.projectInfo.projectName == 'undefined'){
                    return false;
                }
                if(app.on_beetle == 'true' && app.app_type == 'tomcat'){
                    return true;
                }
            }
        }else {
            if(app.on_beetle == 'false'
                || app.app_type == 'adempiere'
                || typeof app.projectInfo == 'undefined'
                || typeof app.editionInfo == 'undefined'){
                return false;
            }
            if(type == 'toTest'){
                if(!app.isRunning
                    && (arrayContains($scope.info.userRole,'dev') || arrayContains($scope.info.userRole,'admin'))
                    && app.editionInfo.editionNum != 'default'
                    && app.editionInfo.editionNum != app.projectInfo.qaTestEdition
                    && app.editionInfo.editionNum != app.projectInfo.testPassEdition){
                    return true;
                }
            }else if(type == 'dis_toTest'){
                if(app.isRunning
                    && (arrayContains($scope.info.userRole,'dev') || arrayContains($scope.info.userRole,'admin'))
                    && app.editionInfo.editionNum != 'default'
                    && app.editionInfo.editionNum != app.projectInfo.qaTestEdition
                    && app.editionInfo.editionNum != app.projectInfo.testPassEdition){
                    return true;
                }
            }else if(type == 'notToTest'){
                if(!app.isRunning
                    && (arrayContains($scope.info.userRole,'dev') || arrayContains($scope.info.userRole,'admin'))
                    && app.editionInfo.editionNum != 'default'
                    && app.editionInfo.editionNum == app.projectInfo.qaTestEdition
                    && app.editionInfo.editionNum != app.projectInfo.testPassEdition){
                    return true;
                }
            }else if(type == 'dis_notToTest'){
                if(app.isRunning
                    && (arrayContains($scope.info.userRole,'dev') || arrayContains($scope.info.userRole,'admin'))
                    && app.editionInfo.editionNum != 'default'
                    && app.editionInfo.editionNum == app.projectInfo.qaTestEdition
                    && app.editionInfo.editionNum != app.projectInfo.testPassEdition){
                    return true;
                }
            }else if(type == 'testPass'){
                if(!app.isRunning
                    && (arrayContains($scope.info.userRole,'qa') || arrayContains($scope.info.userRole,'admin'))
                    && app.editionInfo.editionNum == app.projectInfo.qaTestEdition
                    && app.editionInfo.editionNum != app.projectInfo.testPassEdition
                    && (app.editionInfo.editionNum != app.projectInfo.pushEdition
                    || app.editionInfo.notTestPass)){
                    return true;
                }
            }else if(type == 'dis_testPass'){
                if(app.isRunning
                    && (arrayContains($scope.info.userRole,'qa') || arrayContains($scope.info.userRole,'admin'))
                    && app.editionInfo.editionNum == app.projectInfo.qaTestEdition
                    && app.editionInfo.editionNum != app.projectInfo.testPassEdition
                    && (app.editionInfo.editionNum != app.projectInfo.pushEdition
                    || app.editionInfo.notTestPass)){
                    return true;
                }
            }else if(type == 'notTestPass'){
                if(!app.isRunning
                    && (arrayContains($scope.info.userRole,'qa') || arrayContains($scope.info.userRole,'admin'))
                    && (app.editionInfo.editionNum == app.projectInfo.testPassEdition
                    || app.editionInfo.editionNum == app.projectInfo.qaTestEdition)
                    && !app.editionInfo.notTestPass){
                    return true;
                }
            }else if(type == 'dis_notTestPass'){
                if(app.isRunning
                    && (arrayContains($scope.info.userRole,'qa') || arrayContains($scope.info.userRole,'admin'))
                    && (app.editionInfo.editionNum == app.projectInfo.testPassEdition
                    || app.editionInfo.editionNum == app.projectInfo.qaTestEdition)
                    && !app.editionInfo.notTestPass){
                    return true;
                }
            }
        }
        return false;
    };

    $scope.doBuild = function (app) {
        if(app.isRunning){
            return;
        }
        $scope.doRun(app);
        app.isRunning = true;
        // app.runTip = "工程构建中";
        app.pipeline_status = '';
        app.last_msg = '';
        $http.post(java_url+'/beetle/project/doBuild', {
            projectName: app.projectInfo.projectName,
            tokenId:getTokenId()
        }).success(function (data) {
            if (data.code != '0') {
                alert(data.desc);
                return;
            };
            getProjectInfo(app);
            $scope.info.buildList.push(app.projectInfo.projectName);
            wsObj.obj.send("project-" + app.projectInfo.projectName + "-build");
        });
    };
    $scope.doRelease = function (app) {

        openDialog(ngDialog, $scope, "确定要发布该版本么?", true, function (flag) {
            if(!flag){
                return;
            }
            release(app);
        });
    };
    
    function release(app) {
        var param = new Object();
        param.package_path = "";
        param.version = "";
        param.sub_path = "";
        if(app.on_beetle == "true") {
            if(typeof app.projectInfo.projectName == 'undefined'
                || typeof app.editionInfo.editionNum == 'undefined'){
                openDialog(ngDialog, $scope, "所选分支或版本不存在,请重新选择!", false, function () {});
                return;
            }

            if (app.editionInfo.editionNum == 'default'
                && app.projectInfo.buildStatus != 'build_success') {
                openDialog(ngDialog, $scope, "该版本尚未构建或构建失败,请构建成功后再发布!", false, function () {});
                return;
            }

            if (app.app_type == 'adempiere') {
                param.package_path = app.projectInfo.projectName + "/" + app.editionInfo.editionNum;
                param.version = app.editionInfo.editionNum;
            } else if (app.app_type == 'tomcat' || app.app_type == 'php') {
                param.package_path = getEditionPath(app.projectInfo.projectName, app.editionInfo.editionNum);
                param.version = app.projectInfo.projectName + "@" + app.editionInfo.editionNum;
                param.sub_path = "/target";
                if (typeof app.editionInfo.nasNum != 'undefined'
                    && app.editionInfo.nasNum != 'undefined'
                    && app.editionInfo.nasNum != ''
                    && app.editionInfo.nasNum != null) {
                    param.sub_path = param.sub_path + "/" + app.editionInfo.nasNum;
                };
            }
        }
        // app.runTip = "应用发布中";
        $scope.runPipeline(app,app.app_id+"_install",param);
    };
    
    $scope.doStop = function (app) {
        openDialog(ngDialog, $scope, "确定要停止该应用么?", true, function (flag) {
            if(!flag){
                return;
            }
            stop(app);
        });
    };
    
    function stop(app) {
        var param = new Object();
        $scope.runPipeline(app,app.app_id+"_stop",param);
    };
    
    $scope.doRestart = function (app) {
        // app.runTip = "正在重启应用";
        // $scope.runPipeline(app,app.app_id+"_restart",param);
        openDialog(ngDialog, $scope, "确定要重启该应用么?", true, function (flag) {
            if(!flag){
                return;
            }
            restart(app);
        });
    };

    function restart(app) {
        var param = new Object();
        var pipeline_name = app.app_id+"_restart";
        $scope.doRun(app);
        app.isRunning = true;
        var ip = $scope.info.vmInfo.ip;
        if(typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == ''){
            alert("虚拟机ip为空!");
            return;
        };
        app.pipeline_status = "running";
        app.last_msg = "";
        $http.get(getUCloudAddress(ip)+"/apps/start?params="+JSON.stringify(param)+"&pipeline_name="+pipeline_name,{
            headers : {'Accept':'application/json'}
        }).success(function (data) {
            app.pipeline_status = data.status;
        }).error(function () {
            $scope.info.vmStatus="error";
        });
    };

    $scope.toTest = function (flag,app) {
        if(app.isRunning){
            return;
        }
        $scope.doRun(app);
        app.isRunning = true;
        // app.runTip = "正在修改提交测试状态";
        app.pipeline_status = '';
        app.last_msg = '';
        $http.post(java_url+'/beetle/uCloud/uCloudToTest', {
            projectName:app.projectInfo.projectName,
            editionNum:app.editionInfo.editionNum,
            toTest:flag,
            tokenId:getTokenId()
        }).success(function (result) {
            app.isRunning = false;
            app.last_msg = "修改提交测试状态成功";
            if(result.code != '0'){
                console.log("提交测试,project="+app.projectInfo.projectName+",edition="+app.editionInfo.editionNum+","+result.desc);
                alert(result.desc);
                app.last_msg = "[ERROR]修改提交测试状态失败."+result.desc;
            };
            app.editionNum = result.data.editionNum;
            getProjectInfo(app);
        });
    };
    $scope.testPass = function (flag,app) {
        if(app.isRunning){
            return;
        }
        $scope.doRun(app);
        app.isRunning = true;
        // app.runTip = "正在修改测试通过状态";
        app.pipeline_status = '';
        app.last_msg = '';
        $http.post(java_url+'/beetle/uCloud/uCloudTestPass', {
            projectName: app.projectInfo.projectName,
            editionNum: app.editionInfo.editionNum,
            testStatus:flag,
            tokenId:getTokenId()
        }).success(function (data) {
            if(!flag){
                app.isRunning = false;
            }
            app.last_msg = '修改测试通过状态成功';
            if(data.code != '0'){
                console.log("测试通过,project="+app.projectInfo.projectName+",edition="+app.editionInfo.editionNum+","+data.desc);
                alert(data.desc);
                app.last_msg = '[ERROR]修改测试通过状态失败.'+data.desc;
            };
            app.editionNum = app.editionInfo.editionNum;
            getProjectInfo(app);
            if(flag){
                $scope.info.buildList.push(app.projectInfo.projectName);
                wsObj.obj.send("project-" + app.projectInfo.projectName + "-build");
            }
        });
    };

    $scope.batchRelease = function () {
        openDialog(ngDialog, $scope, "将跳过未构建的应用,确认吗?", true, function (val) {
            if(!val){
                return;
            }
            angular.forEach($scope.info.apps,function (app) {
                if(app.check){
                    if(app.on_beetle == "true") {
                        if(typeof app.projectInfo != 'undefined'
                            && typeof app.editionInfo != 'undefined'
                            && typeof app.projectInfo.projectName != 'undefined'
                            && typeof app.editionInfo.editionNum != 'undefined'){
                            if (app.editionInfo.editionNum != 'default'
                                || (app.editionInfo.editionNum == 'default'
                                && app.projectInfo.buildStatus == 'build_success')){
                                release(app);
                            }
                        }
                    }else{
                        release(app);
                    }
                }
            });
        });
    };

    //批量重启应用
    $scope.batchRestart = function () {
        openDialog(ngDialog, $scope, "将跳过php应用和执行中的应用,确认吗?", true, function (val) {
            if(!val){
                return;
            }
            angular.forEach($scope.info.apps,function (app) {
                if(app.check && app.app_type != 'php' && !app.isRunning){
                    // $scope.doRestart(app);
                    restart(app);
                }
            });
        });
    };

    $scope.batchStop = function () {
        openDialog(ngDialog, $scope, "将跳过php应用和执行中的应用,确认吗?", true, function (val) {
            if(!val){
                return;
            }
            angular.forEach($scope.info.apps,function (app) {
                if(app.check && app.app_type != 'php' && !app.isRunning){
                    // $scope.doRestart(app);
                    stop(app);
                }
            });
        });
    };

    //刷新选中工程的信息
    function getProjectInfo(app) {
        if(typeof app.projectInfo == 'undefined'
            || app.editionInfo == 'undefined'){
            return;
        }
        $http.post(java_url+'/beetle/project/projectListByTrunk',{
            tokenId:getTokenId(),
            trunkName:app.app_name
        }).success(function (data) {
            if(data.code=='0'){
                app.projectList=data.data.list;
                angular.forEach(app.projectList,function (pro) {
                    if(pro.projectName == app.projectInfo.projectName){
                        app.projectInfo = pro;
                        app.editionNum = app.editionInfo.editionNum;
                        $scope.projectChange(app);
                    }
                });
            }
        });

    };

    function getZones() {
        var ip = $scope.info.vmInfo.ip;
        if(typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == ''){
            alert("虚拟机ip为空!");
            return;
        };

        $http.get(getUCloudAddress(ip)+"/zones/",{
            headers : {'Accept':'application/json'}
        }).success(function (data) {
            $scope.info.vmStatus="running";
            $scope.info.zones=data;
            if($scope.info.zones.length > 0){
                $scope.tabClick(0,$scope.info.zones[0]);
            }
        }).error(function () {
            $scope.info.vmStatus="error";
        });
    };

    //根据app列表查询beetle版本信息
    function getAppInfo() {
        if($scope.info.apps.length == 0){
            return;
        }

        var param = [];
        angular.forEach($scope.info.apps,function (app) {
            if(app.on_beetle == 'true'){
                var obj = new Object();
                obj.name = app.app_name;
                obj.version = app.version;
                obj.type = app.app_type;
                param.push(obj);
            }
        });

        $http.post(java_url+'/beetle/uCloud/getUCloudProjectInfo', {
            tokenId:getTokenId(),
            param:JSON.stringify(param)
        }).success(function (data) {
            angular.forEach($scope.info.apps,function (app) {
                angular.forEach(data.data.list,function (data_app) {
                    if(app.app_name == data_app.trunkName){
                        app.projectList = data_app.projectList;
                        app.projectInfo = data_app.projectInfo;
                        app.editionList = data_app.editionList;
                        app.editionInfo = data_app.editionInfo;
                        app.onlineVersion = data_app.onlineVersion;
                        app.qaTestVersion = data_app.qaTestVersion;
                    }
                });
            });
            $('#tbody').css('height',($(window).height()-$('#header').height()
                -$('#myTab').height()-$('#thead').height()-150)+'px');
        });
    };

    $scope.runPipeline = function(app,pipeline_name,param) {
        // if(app.isRunning){
        //     return;
        // }
        $scope.doRun(app);
        app.isRunning = true;
        var ip = $scope.info.vmInfo.ip;
        if(typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == ''){
            alert("虚拟机ip为空!");
            return;
        };
        app.pipeline_status = "running";
        app.last_msg = "";
        $http.get(getUCloudAddress(ip)+"/apps/start?params="+JSON.stringify(param)+"&pipeline_name="+pipeline_name,{
            headers : {'Accept':'application/json'}
        }).success(function (data) {
            app.pipeline_status = data.status;
        }).error(function () {
            $scope.info.vmStatus="error";
        });
    };

    //数据库版本和工程版本图标显示
    $scope.showVersionIcon = function (app) {
        app.versionTip = '<div class="popover_div"><table class="table table-bordered popover_table">';
        if(app.db_dump_create_date == null
            || app.db_dump_create_date == 'null'){
            app.versionTip += '<tr><td class="popover_table_td">数据版本时间戳:</td><td>无</td></tr>';
        }else {
            app.versionTip += '<tr><td class="popover_table_td">数据版本时间戳:</td><td>'+app.db_dump_create_date+'</td></tr>';
        }
        if(app.app_package_create_date == null
            || app.app_package_create_date == 'null'){
            app.versionTip += '<tr><td class="popover_table_td">应用版本时间戳:</td><td>无</td></tr>';
        }else {
            app.versionTip += '<tr><td class="popover_table_td">应用版本时间戳:</td><td>'+app.app_package_create_date+'</td></tr>';
        }

        if(app.version == '-1') {
            app.versionTip += '<tr><td class="popover_table_td">应用版本:</td><td>未发布过版本</td></tr>';
        }else {
            if(app.version.indexOf("@") != -1){
                app.versionTip += '<tr><td class="popover_table_td">应用版本:</td><td>'+app.version.split("@")[0]
                    +'<br>'+app.version.split("@")[1]+'</td></tr>';
            }else {
                app.versionTip += '<tr><td class="popover_table_td">应用版本:</td><td>'+app.version +'</td></tr>';
            }
        }

        var rtn = "";
        var desc = "";
        if(app.db_type == null
            || app.db_type == ''
            || app.db_name == null
            || app.db_name == ''){
            desc = "当前应用没有使用数据库.";
            rtn = "true";
        }else if(app.db_dump_create_date == null
            || app.db_dump_create_date == 'null'
            || app.app_package_create_date == null
            || app.app_package_create_date == 'null'){
            desc = "数据库导出时间或工程版本创建时间不存在";
            rtn = 'false';
        }
        if(rtn == ""){
            var date = (parse(app.db_dump_create_date).valueOf() - parse(app.app_package_create_date).valueOf())/(1000*60*60*24);
            // var date = (parse('20161223-120210').valueOf() - parse('20161212-120210').valueOf())/(1000*60*60*24);
            // if(date >= ucloud_db_edition_date){
            //     desc = "数据库版本时间与工程版本创建时间间隔超过"+ucloud_db_edition_date+"天.";
            //     rtn = 'false';
            // }else if(date < 0){
            //     desc = "工程版本比数据库版本较新,请检查工程版本是否修改过数据库.";
            //     rtn = 'warn';
            // }else{
            //     desc = "数据库版本时间与工程版本创建时间间隔在"+ucloud_db_edition_date+"天内.";
            //     rtn = 'true';
            // }
            if(date < 0){
                desc = "数据库版本比工程版本旧.若当前工程为要开发工程,请更新数据库.若当前工程为环境依赖工程,可忽略.";
                rtn = 'false';
            }else {
                desc = "数据库版本比工程版本新";
                rtn = 'true';
            }
        }
        if(desc != ""){
            app.versionTip += '<tr><td class="popover_table_td">描述:</td><td>'+desc+'</td></tr>';
        }
        app.versionTip += '</table></div>';
        return rtn;
    };
    //应用状态中文显示
    function getAppStatusZN(app){
        if(typeof app.status == 'undefined' || app.status == 'undefined'
            || app.status == null ||app.status == 'null'){
            return "";
        }
        if(app.status == "unavailable"){
            return "未部署";
        }else if(app.status == "ready"){
            return "已部署";
        }else if(app.running_pipeline != null){
            return "执行操作";
        }
    };
    //展示应用状态图标
    $scope.showStatusIcon = function (app) {
        app.statusTip = '<table class="table table-bordered">';
        if(typeof app.status == 'undefined' || app.status == 'undefined'
            || app.status == null ||app.status == 'null'){
            app.statusTip += '<tr><td>应用状态:</td><td></td></tr>';
        }else {
            app.statusTip += '<tr><td>应用状态:</td><td>'+getAppStatusZN(app);+'</td></tr>';
        }
        if(app.running_pipeline != null){
            var pipName = app.running_pipeline.replace("_install","安装").replace("_stop","停应用").replace("_restart","重启应用");
            app.statusTip += '<tr><td>任务状态:</td><td>'+pipName+'</td></tr>';
        }else {
            app.statusTip += '<tr><td>任务状态:</td><td></td></tr>';
        }
        app.statusTip += '</table>';

        if(app.isRunning){
        // if(app.running_pipeline != null || app.isRunning){
            return "";
        }else if(app.is_running){
            return "running";
        }else if(!app.is_running){
            return "stop";
        }

        return '';
    };

    //展示应用信息图标
    $scope.showInfoIcon = function (app) {
        var rtn = "info";
        var msg = "";
        if(typeof app.last_msg != 'undefined' && app.last_msg != null && app.last_msg != ''){
            app.last_msg = app.last_msg.replace(new RegExp(/(\\n)/g),"<br>").replace(app.app_id+"_install","安装"+app.app_name).replace(app.app_id+"_stop","停止应用"+app.app_name).replace(app.app_id+"_restart","重启应用"+app.app_name);
            if(app.last_msg.indexOf("[ERROR]") == 0){
                msg = app.last_msg.substring(7,app.last_msg.length);
                rtn = "error";
            }else if(app.last_msg.indexOf("[WARN]") == 0){
                msg = app.last_msg.substring(6,app.last_msg.length);
                rtn = "warn";
            }else if(app.last_msg.indexOf("[INFO]") == 0){
                msg = app.last_msg.substring(6,app.last_msg.length);
            }else {
                msg = app.last_msg;
            }
        }
        setTimeout(function () {
            var info = '<div style="overflow: auto;">'+msg+'</div>';
            app.infoTip = $sce.trustAsHtml(info);

        },100);
        return rtn;
    };
    
    $scope.openApp = function (app) {
        window.open("http://"+$scope.info.vmInfo.ip+":"+app.port+app.ucUrl);
    };

    $scope.openShowLogModal=function (type,size) {
        var ip = $scope.info.vmInfo.ip;
        if(typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == ''){
            alert("虚拟机ip为空!");
            return;
        };
        var info = this.app;
        info.type=type;
        info.ip=ip;
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'ucLogModal.html',
            controller: 'UCLogModalCtrl',
            size: size,
            resolve: {
                info:function () {
                    return info;
                }
            }
        });
    };
    //修复dep
    $scope.fixApp = function (app) {
        var ip = $scope.info.vmInfo.ip;
        if(typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == ''){
            alert("虚拟机ip为空!");
            return;
        };
        alert("adfas");
        // $http.get(getUCloudAddress(ip)+"/apps/?zone_code="+zone.zone_code,{
        //     headers : {'Accept':'application/json'},
        // }).success(function (data) {
        // }).error(function () {
        //     $scope.info.vmStatus="error";
        // });
    };
    $scope.toRunSql=function (size) {
        var ip = $scope.info.vmInfo.ip;
        if(typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == ''){
            alert("虚拟机ip为空!");
            return;
        };
        var info = this.app;
        info.ip=ip;
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'sqlModal.html',
            controller: 'UCSqlCtrl',
            size: size,
            keyboard:false,
            backdrop:'static',
            resolve: {
                info:function () {
                    return info;
                }
            }
        });
    };
    
    $scope.doRun = function (app) {
        app.doRun = true;
        if(!arrayContains($scope.info.doRunList,app.app_id)){
            $scope.info.doRunList.push(app.app_id);
        }
    };

    //检查工程配置文件是否正确
    $scope.doCheck = function (app) {
        if(app.isRunning){
            return;
        }
        $scope.doRun(app);
        app.isRunning = true;
        app.last_msg = '开始检查配置文件是否正确';
        $http.post(java_url+'/beetle/uCloud/checkConfig', {
            projectName: app.projectInfo.projectName,
            envName:$scope.info.selectZone.zone_code,
            tokenId:getTokenId()
        }).success(function (data) {
            app.isRunning = false;
            app.last_msg = data.desc;
        });
    };

    //重新导入应用数据库数据
    $scope.reImportData = function (app) {
        var ip = $scope.info.vmInfo.ip;
        if(typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == ''){
            alert("虚拟机ip为空!");
            return;
        };
        var db_name = 'pip-db:'+app.db_type+':'+app.db_name+':demo';

        openDialog(ngDialog, $scope, "确定要重新导入"+app.app_name+"的数据库么?", true, function (val) {
            if(!val){
                return;
            }
            openDialog(ngDialog, $scope, "重新导入后,之前的数据将删除,是否确认导入？", true, function (val) {
                if(!val){
                    return;
                }
                $.ajax({
                    type:"put",
                    url:getUCloudAddress(ip)+'/database/import?db_name='+db_name,
                    dataType : "JSON",
                    contentType : "application/json",
                    async:false,
                    success: function(){
                        openDialog(ngDialog, $scope, "重新导入成功，请在日志查看导入结果!", false, function (val){});
                    }
                });
            });
        });
    };

    $scope.openApi = function () {
        window.open("http://"+$scope.info.vmInfo.ip+":5000/api/v1");
    };

    $scope.reloadApp = function () {
        var ip = $scope.info.vmInfo.ip;
        if(typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == ''){
            alert("虚拟机ip为空!");
            return;
        };
        $http.get(getUCloudAddress(ip)+"/apps/reflush_apps",{
            headers : {'Accept':'application/json'}
        }).success(function () {
            window.location.reload();
        }).error(function () {
            $scope.info.vmStatus="error";
        });
    };
});
myApp.controller('UCLogModalCtrl', function ($scope, $uibModalInstance,$http,info,$interval,$sce) {
    $scope.timer = null;
    $scope.log = "";
    // $scope.$on("$destroy", function() {
    //     if($scope.timer){
    //         $interval.cancel($scope.timer);
    //     }
    // });
    var type = info.type;
    //查询日志
    function getUCLog() {
        var app_id = info.app_id;
        var ip = info.ip;
        $.ajax({
            type: "put",
            url: getUCloudAddress(ip)+'/apps/'+app_id+'/logs?log_type='+type,
            dataType : "JSON",
            contentType : "application/json",
            async:false,
            success: function(data){
                $scope.log = "";
                $scope.log = $sce.trustAsHtml(data);
            }
        });

        // if(!$scope.timer){
        //     $scope.timer=$interval(function(){
        //         var logDiv = document.getElementById("log_div");
        //         logDiv.scrollTop = logDiv.scrollHeight;
        //         getUCLog();
        //     },2000);
        // }
    };
    
    function getBuildLog() {
        $http.post(java_url+'/beetle/project/getBuildLog', {
            projectName: info.projectInfo.projectName,
            tokenId:getTokenId()
        }).success(function (data) {
            $scope.log = "";
            $scope.log = data.data.log;
        });
        // if(!$scope.timer){
        //     $scope.timer=$interval(function(){
        //         var logDiv = document.getElementById("log_div");
        //         logDiv.scrollTop = logDiv.scrollHeight;
        //         getBuildLog();
        //     },2000);
        // }
    };

    $scope.getLog = function () {
        if(type != 'build'){
            getUCLog();
        }else{
            getBuildLog();
        }
    };
    $scope.getLog();

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});
myApp.controller('UCSqlCtrl', function ($scope, $uibModalInstance,$http,info) {
    $scope.info={};
    $scope.info.sql="";
    $scope.info.runIng=false;
    $scope.runSql = function(){
        if($scope.info.runIng){
            return;
        }
        $scope.info.runIng=true;
        var app_id = info.app_id;
        // $.ajax({
        //     type: "put",
        //     url: getUCloudAddress(info.ip)+'/apps/'+app_id+'/logs?log_type='+type,
        //     dataType : "JSON",
        //     contentType : "application/json",
        //     async:false,
        //     success: function(data){
        //     }
        // });
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});